<template>
    <div class="common-layout">
        <el-container>
            <el-header height="75px">
                <head-page></head-page>
            </el-header>
            <el-button style="width: 10%; margin-left: 2%; margin-bottom: -1%" :icon="Position" @click="jump">高级搜索
            </el-button>
            <el-main>
                <div>
                    <el-carousel trigger="click" indicator-position="outside">
                        <el-carousel-item v-for="item in imageList" :key="item.name">
                            <img :src="item.src" style="height: 350px; width: 1000px" :title="item.title"/>
                        </el-carousel-item>
                    </el-carousel>
                    <div style="position: absolute ; z-index: 800" class="radius">
                        <div style="padding: 15px">
                            <el-text style="font-size: 30px; padding: 5px; font-family: 'Arial Rounded MT Bold',serif;
                                        color: #cecece; font-weight: bold">Vertilegal
                            </el-text>
                            <el-text style="font-size: 25px; font-family: 微软雅黑,sans-serif;
                                    color: #cecece">更加方便直观的律师推荐垂直搜索
                            </el-text>
                        </div>
                        <el-row class="input">
                            <el-col :span="12">
                                <el-input
                                    v-model="input"
                                    :autosize="{ minRows: 2, maxRows: 4 }"
                                    maxlength="100"
                                    show-word-limit
                                    type="textarea"
                                    placeholder="请输入案件关键词，如：离婚、经济纠纷、知识产权......"
                                >
                                </el-input>
                            </el-col>
                            <el-col :span="10" style="margin-left: 15px">
                                <div style="width: 55%">
                                    <el-cascader :options='provinceAndCityData' v-model='selectedOptions'
                                                 placeholder="请选择律师所在的城市"
                                                 @change='handleChange'></el-cascader>
                                </div>
                            </el-col>
                            <el-col :span="1" style="margin-left: -17%">
                                <el-button type="warning" :icon="Search" @click="search()">搜 索</el-button>
                            </el-col>
                        </el-row>
                    </div>
                    <el-header></el-header>
                    <br><br><br>
                    <el-divider>
                        <el-icon>
                            <star-filled/>
                        </el-icon>
                        欢迎使用 AI 问答功能
                        <el-icon>
                            <star-filled/>
                        </el-icon>
                    </el-divider>
                </div>
            </el-main>
        </el-container>

    </div>

    <div class="chat-container">
        <div v-for="(message, index) in messages" :key="index" class="message"
             :class="{'ai-message': message.sender === 'ai', 'user-message': message.sender === 'user'}">
            <div class="message-content">{{ message.text }}</div>
        </div>
        <!-- 输入区域 -->
        <div class="input-area">
            <el-input
                v-model="chatai"
                maxlength="500"
                show-word-limit
                placeholder="请输入案件描述，如：离婚、经济纠纷、知识产权......"
                style="width: 80%;"
            >
            </el-input>
            <el-button :type="'info'" style="margin-left: 2%" @click="aiAPI">发 送</el-button>
        </div>
    </div>
</template>


<script setup>
import {onMounted, ref} from "vue";
import {codeToText, provinceAndCityData} from 'element-china-area-data'
import {Position, Search, StarFilled} from "@element-plus/icons-vue";
import router from "@/router";
import {ElMessage} from "element-plus";
import axios from 'axios'
import HeadPage from "@/components/HeadPage.vue";

const input = ref('')
const chatai = ref('')
const messages = ref([])
const imageList = ref([
    {
        name: "back1",
        src: require("@/assets/back1.jpg"),
        title: "法庭"
    },
    {
        name: "back2",
        src: require("@/assets/back2.png"),
        title: "法庭"
    },
    {
        name: "back3",
        src: require("@/assets/back3.jpg"),
        title: "法庭"
    },
    {
        name: "back4",
        src: require("@/assets/back4.jpg"),
        title: "法庭"
    }
]);

let selectedOptions = ref([''])
let location = ref('');
const handleChange = () => {
    for (let i = 0; i < selectedOptions.value.length; i++) {
        location.value += codeToText[(selectedOptions.value[i])];
    }
    console.log(location.value)//打印区域码所对应的属性值即中文地址
}
let uid = '-1'
onMounted(() => {
    getUid()
    console.log(uid)
});

function getUid() {
    let ch = window.location.href;
    if (ch.length > 22) {
        uid = ch.substring(26)
        if (uid.charAt(uid.length - 1) === '\\') {
            uid = uid.substring(0, uid.length - 1)
        }
    }
}

function jump() {
    getUid()
    router.push('/log/' + uid + '/lawyer/' + "全国")
}

const search = () => {
    getUid()
    console.log(uid)
    if (location.value !== '') {
        input.value = input.value + location.value;
    }
    if (input.value === '') {
        ElMessage.warning("请输入关键字搜索")
    } else {
        console.log(input.value)
        router.push('/log/' + uid + '/lawyer/' + input.value)
    }
}
let answer = ref('')
const token = "24.31577262d3485cc4ebcf784252ceb6f6.2592000.1706023578.282335-45661100";// 替换这里

async function ask(question) {
    const url = `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=${token}`;
    const payload = {
        messages: [{role: 'user', content: question}]
    };
    const headers = {
        'Content-Type': 'application/json'
    };

    try {
        const response = await axios.post(url, payload, {headers});
        return response.data;
    } catch (error) {
        ElMessage.error('请求 AI API 时出错:', error.message);
        if (error.response) {
            // 请求已发出，服务器以状态码响应
            ElMessage.error('响应状态码:', error.response.status);
            ElMessage.error('响应数据:', error.response.data);
        } else if (error.request) {
            // 请求已发出，但未收到响应
            ElMessage.error('未收到响应:', error.request);
        } else {
            // 发送请求时出现了一些问题
            ElMessage.error('请求错误:', error.message);
        }
        throw error;
    }
}

async function aiAPI() {
    getUid();
    if (uid === '-1') {
        ElMessage.warning('当前功能仅为注册用户提供，请先进行登录');
        return;
    } else if (chatai.value === '') {
        ElMessage.warning('问答内容不能为空');
        return;
    }
    try {
        ElMessage.success('请稍等...')
        // 发送请求到文心一言的 API
        const data = await ask(chatai.value);

        // 设置答案到 answer.value
        answer.value = data.result;
        // 添加用户的问题和 AI 的回答到 messages 数组
        messages.value.push({text: chatai.value, sender: 'user'});
        messages.value.push({text: data.result, sender: 'ai'});

        // 清空输入框
        chatai.value = '';
    } catch (error) {
        ElMessage.error('请求 AI API 时出错: 账户已欠费');
    }
}

</script>

<style scoped lang="scss">
$primary-color: #0078ff;
$background-color: #f5f5f5;
$text-color: #333;


.el-carousel__item h3 {
    color: #212121;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
    text-align: center;
}

.el-carousel__item:nth-child(2n) {
    background-color: #3b3b3b;
}

.el-carousel__item:nth-child(2n + 1) {
    background-color: #2c2c2c;
}

.radius {
    margin-left: 10%;
    margin-top: -50px;
    background-color: #3b3b3b;
    width: 70%;
    height: 150px;
    border: 1px solid #282828;
    border-radius: 2em/5em;
    box-shadow: #6b6b6b 1px 2px 1px 1px;
}

.input {
    margin-top: 1%;
    margin-left: 6%;
    width: 100%;
}

.chat-container {
    display: flex;
    flex-direction: column;
    max-height: 600px;
    overflow-y: auto;
}

/* 调整聊天气泡的样式，使其更现代化 */
.message {
    padding: 12px 16px;
    margin-bottom: 10px;
    border-radius: 18px;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
    max-width: 75%;
    word-wrap: break-word;
    text-align: left; /* 设置文本对齐为左对齐 */
}

.ai-message {
    background-color: #ffffff;
    align-self: flex-start;
    border: 1px solid #eaeaea;
}

.user-message {
    background-color: #0078ff;
    color: white;
    align-self: flex-end;
    border: none;
}

/* 输入区域的样式 */
//.input-area {
//    display: flex;
//    justify-content: center; /* 水平居中 */
//    padding: 15px;
//    background-color: #fff;
//    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
//    position: fixed;
//    bottom: 0;
//    left: 0;
//    right: 0;
//    z-index: 1000;
//}
.input-area {
    background-color: #fff;
    padding: 20px;
    margin: 40px auto; /* 水平居中并提供上下间距 */
    width: 80%; /* 根据实际情况调整 */
    max-width: 800px; /* 根据实际情况调整 */
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 30px;
    display: flex;
    justify-content: space-between; /* 使元素均匀分布 */
}

.el-input,
.el-button {
    border-radius: 18px;
    border: 1px solid #dcdfe6;
}

.el-button {
    background-color: $primary-color;
    color: white;

    &:hover {
        background-color: lighten($primary-color, 5%);
    }
}

/* 滚动条样式 */
.chat-container {
    padding-bottom: 70px; /* 预留输入区域的空间 */
    overflow-y: auto;
}

/* 自定义滚动条（可选） */
.chat-container::-webkit-scrollbar {
    width: 5px;
}

.chat-container::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #ccc;
}

.chat-container::-webkit-scrollbar-track {
    background-color: #f5f5f5;
}

/* 优化carousel显示 */
.el-carousel__item img {
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}


/* 调整搜索按钮样式 */
.el-button {
    border: none;
    background-color: #0078ff;
    color: white;
    /* 其他样式 */
}

/* 调整header的样式 */
.el-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

</style>
